package cn.lzd.ui.widgets;

import android.R;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.webkit.*;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.core.content.ContextCompat;

/**
 * 通用 WebView
 */
public class CommonWebView extends WebView {
    public CommonWebView(Context context) {
        super(getFixedContext(context));
        initView();
    }

    public CommonWebView(Context context, AttributeSet attrs) {
        super(getFixedContext(context), attrs);
        initView();
    }

    public CommonWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(getFixedContext(context), attrs, defStyleAttr);
        initView();
    }

    private static Context getFixedContext(Context context) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            return context.createConfigurationContext(new Configuration());
        } else {
            return context;
        }
    }

    private ProgressBar progressBar;
    private IEventListener eventListener;

    private void initView() {
        setHorizontalScrollBarEnabled(false);
        setVerticalScrollBarEnabled(false);
        progressBar = new ProgressBar(getContext(), null, R.attr.progressBarStyleHorizontal);
        progressBar.setMax(100);
        progressBar.setProgressDrawable(ContextCompat.getDrawable(getContext(), cn.lzd.ui.R.drawable.uibase_progressbar));
        initWebViewSettings();
    }

    @SuppressLint({"ClickableViewAccessibility", "SetJavaScriptEnabled"})
    private void initWebViewSettings() {
        setBackgroundColor(ContextCompat.getColor(getContext(), R.color.white));
        setWebViewClient(initWebViewClient());
        setWebChromeClient(chromeClient);
        setDownloadListener(mDownloadListener);
        setClickable(true);
        setOnTouchListener((v, event) -> false);
        WebSettings webSetting = getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setBuiltInZoomControls(false);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(false);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setTextZoom(100);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setMediaPlaybackRequiresUserGesture(false);
        webSetting.setSupportMultipleWindows(false);
    }

    private WebViewClient initWebViewClient() {
        return new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                eventListener.onPageFinished();
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http") || url.startsWith("https") || url.startsWith("ftp")) {
                    return false;
                } else {
                    try {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        view.getContext().startActivity(intent);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(view.getContext(), "手机还没有安装支持打开此网页的应用！", Toast.LENGTH_SHORT).show();
                    }
                    return true;
                }
            }
        };
    }

    public void syncCookie(String url, String cookie) {
        CookieSyncManager.createInstance(getContext());
        if (!TextUtils.isEmpty(url)) {
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setAcceptCookie(true);
            cookieManager.removeSessionCookie();// 移除
            cookieManager.removeAllCookie();

            //这里的拼接方式是伪代码
            String[] split = cookie.split(";");
            for (String string : split) {
                //为url设置cookie
                // ajax方式下  cookie后面的分号会丢失
                cookieManager.setCookie(url, string);
            }
            String newCookie = cookieManager.getCookie(url);
            //sdk21之后CookieSyncManager被抛弃了，换成了CookieManager来进行管理。
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                CookieSyncManager.getInstance().sync();//同步cookie
            } else {
                CookieManager.getInstance().flush();
            }
        }
    }

    private final WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (eventListener != null) {
                eventListener.onReceivedTitle(title);
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            progressBar.setProgress(newProgress);
            progressBar.setVisibility(newProgress == 100 ? GONE : VISIBLE);
        }
    };

    DownloadListener mDownloadListener = (url, a, b, c, d) -> {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        getContext().startActivity(intent);
    };

    public void setEventListener(IEventListener eventListener) {
        this.eventListener = eventListener;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getAction() != KeyEvent.ACTION_UP && canGoBack()) {
            loadBackJS(); // goBack()表示返回WebView的上一页面
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    private void loadBackJS() {
        String url = getUrl();
        if (url.contains("pay2?sus")) {
            this.loadUrl("javascript:backItem()");
        } else {
            goBack();
        }
    }

    public interface IEventListener {
        void onReceivedTitle(String title);

        void onPageFinished();
    }
}
